// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2005-4-29

#include "stdafx.h"
#include "strcrypt.h"
#include <stdlib.h>

namespace JoyGuard
{

//##ModelId=44C4B60D0283
void StrCrypt::EncryptData(void* dst, const void* src, size_t len)
{
    for(; len >= sizeof(DWORD); len -= sizeof(DWORD))
    {
        DWORD s = *(DWORD*)src;
        src = (DWORD*)src+1;
        s = _rotl(s, 8);
        s = ~s;
        *(DWORD*)dst = s;
        dst = (DWORD*)dst+1;
    }

    for(; len > 0; len -= 1)
    {
        BYTE s = *(BYTE*)src;
        src = (BYTE*)src+1;
        s = ~s;
        *(BYTE*)dst = s;
        dst = (BYTE*)dst+1;
    }
}

//##ModelId=44C4B60D0292
void StrCrypt::DecryptData(void* dst, const void* src, size_t len)
{
    for(; len >= sizeof(DWORD); len -= sizeof(DWORD))
    {
        DWORD s = *(DWORD*)src;
        src = (DWORD*)src+1;
        s = ~s;
        s = _rotr(s, 8);
        *(DWORD*)dst = s;
        dst = (DWORD*)dst+1;
    }

    for(; len > 0; len -= 1)
    {
        BYTE s = *(BYTE*)src;
        src = (BYTE*)src+1;
        s = ~s;
        *(BYTE*)dst = s;
        dst = (BYTE*)dst+1;
    }
}

//##ModelId=44C4B60D0297
void StrCrypt::Encrypt(char* dst, const char* src, size_t len)
{
    if(len == size_t(-1))
    {
        len = ::strlen(src);
    }
    EncryptData(dst, src, len);
}

//##ModelId=44C4B60D02A2
void StrCrypt::Decrypt(char* dst, const char* src, size_t len)
{
    if(len == size_t(-1))
    {
        len = ::strlen(src);
    }
    DecryptData(dst, src, len);
}

//##ModelId=44C4B60D02A7
void StrCrypt::Encrypt(wchar_t* dst, const wchar_t* src, size_t len)
{
    if(len == size_t(-1))
    {
        len = ::wcslen(src);
    }
    EncryptData(dst, src, len*2);
}

//##ModelId=44C4B60D02B2
void StrCrypt::Decrypt(wchar_t* dst, const wchar_t* src, size_t len)
{
    if(len == size_t(-1))
    {
        len = ::wcslen(src);
    }
    DecryptData(dst, src, len*2);
}

} // namespace JoyGuard
